package util;

import cn.hutool.core.collection.ListUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 4G网络检测工具类（仅支持Linux系统）
 */
public class LTEChecker {

    // 4G模块常见的网络接口名
    private static final List<String> LTE_INTERFACES = ListUtil.of("wwan0", "wwan1", "ppp0", "ppp1", "enx");

    /**
     * 检查当前系统是否存在活跃的4G网络
     * @return true：存在4G网络；false：不存在或检测失败
     */
    public static boolean has4GNetwork() {
        // 步骤1：检查是否存在4G典型网络接口且已激活
        String activeLTEInterface = getActiveLTEInterface();
        if (activeLTEInterface!=null) {
            // 步骤2：进一步通过调制解调器状态确认（可选，增强准确性）
            return isConnected(activeLTEInterface);
        }
        return false;
    }

    private static boolean isConnected(String interfaceName) {
        try{
            String[] command = {
                    "sh", "-c",
                    "ping -I " + interfaceName + " -c 2 -W 3  www.baidu.com >/dev/null 2>&1 && echo 'SUCCESS' || echo 'FAIL'"
            };
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream())
            );

            String result = reader.readLine();
            reader.close();

            boolean finished = process.waitFor(8, TimeUnit.SECONDS);
            if (!finished) {
                process.destroyForcibly();
                return false;
            }

            return "SUCCESS".equals(result);
        }catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查是否存在活跃的4G网络接口（有IP地址）
     */
    private static String getActiveLTEInterface() {
        try {
            // 执行ip addr命令，获取网络接口信息
            Process process = Runtime.getRuntime().exec("ip addr show");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream())
            );

            String line;
            String currentInterface = null;

//            System.out.println("ip addr show:");
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                // 匹配网络接口名（如"3: wwan0:"）
                if (line.matches("^\\d+:\\s+\\w+:.*")) {
                    currentInterface = line.split(":")[1].trim();
                }
//                System.out.println("..." + line);
                // 检查接口是否有IP地址（inet字段）
                if (currentInterface != null) {
                    for (String lteInterface : LTE_INTERFACES) {
                        if (currentInterface.contains(lteInterface)) {
                            return currentInterface;
                        }
                    }
                }
            }

            reader.close();
            process.waitFor();
            return currentInterface;

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }


    // 测试方法
    public static void main(String[] args) {
        System.out.println("是否存在4G网络：" + has4GNetwork());
    }
}